﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FusionCharts.WebParts
{
    class ChartXmlWriter
    {
        private Plots _plots = null;
        private string _chartTitle = "";
        private string _xTitle = "";
        private string _yTitle = "";
        private string _colors = "";

        public ChartXmlWriter(Plots plots, string ChartTitle, string XTitle, string YTitle, string Colors)
        {
            _plots = plots;
            _chartTitle = ChartTitle;
            _xTitle = XTitle;
            _yTitle = YTitle;
            _colors = Colors;
        }
        /// <summary>
        /// Generate the nice XML output for fusion charts
        /// </summary>
        public string WriteXml()
        {
            // We first convert color (string) into a nice array
            string[] separator = { ";" };
            string[] colorsArray = _colors.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            StringBuilder sb = new StringBuilder();
            // We open the graph tag with a few parameters
            sb.AppendLine("<graph caption='" + _chartTitle + "' xAxisName='" + _xTitle + "' yAxisName='" + _yTitle + "'>");

            for (int i = 0; i < _plots.Count(); i++)
            {
                // We try to compute the color
                string color = "";
                try
                {
                    color = colorsArray[i % (colorsArray.Length)]; // computes to color to use
                }
                catch { } // if we fail we skip the error, default color will be used

                // We add a line to the XML
                sb.Append("<set name='" + _plots.GetX(i) + "' value='" + _plots.GetY(i).ToString() + "'");
                if (color != "") sb.Append(" color='" + color + "'");
                sb.AppendLine(" />");
            }

            // We close the graph tag opened previously
            sb.AppendLine("</graph>");

            // We finally return the xml data
            return sb.ToString();
        }
    }
}
